package library.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import library.admin.domain.dto.PageDTO;
import library.admin.domain.po.User;
import library.admin.domain.query.UserPageQuery;
import library.admin.domain.request.SaveUserRequest;
import library.admin.domain.request.UpdateUserStatusRequest;
import library.admin.domain.vo.UserVO;
import library.admin.mapper.UsersMapper;
import library.admin.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User> implements IUsersService {

    @Override
    public User getByUsername(String username) {
        User users = lambdaQuery().eq(User::getUsername, username).one();
        if (users == null) {
            throw new IllegalArgumentException(username + " 用户不存在");
        }
        return users;
    }

    @Override
    public void login(String username, String password) {
        User users = getByUsername(username);
        if (!users.getPassword().equals(password)) {
            throw new IllegalArgumentException("密码错误");
        }
    }
    
    @Override
    public PageDTO<UserVO> queryUsersByPage(UserPageQuery pageQuery) {
        Page<User> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(pageQuery.getUsername())) {
            queryWrapper.like(User::getUsername, pageQuery.getUsername());
        }
        if (StringUtils.hasText(pageQuery.getName())) {
            queryWrapper.like(User::getName, pageQuery.getName());
        }
        if (StringUtils.hasText(pageQuery.getEmail())) {
            queryWrapper.like(User::getEmail, pageQuery.getEmail());
        }
        if (pageQuery.getRole() != null) {
            queryWrapper.eq(User::getRole, pageQuery.getRole());
        }
        
        // 执行查询
        Page<User> userPage = page(page, queryWrapper);
        
        // 转换为VO列表
        List<UserVO> voList = userPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建分页结果
        PageDTO<UserVO> pageDTO = new PageDTO<>();
        pageDTO.setList(voList);
        pageDTO.setTotal(userPage.getTotal());
        pageDTO.setPages(userPage.getPages());
        
        return pageDTO;
    }
    
    @Override
    @Transactional
    public Long saveUser(SaveUserRequest request) {
        // 检查用户名是否已存在
        if (existsByUsername(request.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 检查电子邮箱是否已存在
        if (StringUtils.hasText(request.getEmail()) && existsByEmail(request.getEmail())) {
            throw new IllegalArgumentException("电子邮箱已被使用");
        }
        
        // 创建用户实体
        User user = new User();
        BeanUtils.copyProperties(request, user);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        
        // 保存用户
        save(user);
        
        return user.getId();
    }
    
    @Override
    @Transactional
    public boolean updateUserStatus(UpdateUserStatusRequest request) {
        User user = getById(request.getId());
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 通过设置特殊字段来标记用户是否启用
        // 由于数据库没有enabled字段，我们可以通过其他方式实现
        // 例如，可以通过设置role为负数来表示禁用状态
        if (!request.getEnabled()) {
            // 禁用用户（将角色设置为负数）
            user.setRole(-Math.abs(user.getRole()));
        } else {
            // 启用用户（将角色恢复为正数）
            user.setRole(Math.abs(user.getRole()));
        }
        
        user.setUpdatedAt(LocalDateTime.now());
        return updateById(user);
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return lambdaQuery()
                .eq(User::getUsername, username)
                .count() > 0;
    }
    
    @Override
    public boolean existsByEmail(String email) {
        return StringUtils.hasText(email) && lambdaQuery()
                .eq(User::getEmail, email)
                .count() > 0;
    }
    
    @Override
    public UserVO getUserDetails(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        return convertToVO(user);
    }
    
    /**
     * 将User实体转换为UserVO视图对象
     *
     * @param user 用户实体
     * @return 用户视图对象
     */
    private UserVO convertToVO(User user) {
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        
        // 设置启用状态（根据role的正负值判断）
        vo.setEnabled(user.getRole() >= 0);
        
        return vo;
    }
}
